﻿using Lightworks.Core.Cache;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Lightworks.Core.Auth
{
    public static class AuthExtensions
    {
        public static IServiceCollection AddJwtAuth(this IServiceCollection services, JwtConfig? config) 
        {
            services.AddSingleton(provider => {
                var cache = provider.GetRequiredService<ICacheService>();
                return new JwtService(cache, config);
            });
            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                .AddJwtBearer(options => {
                    var secretByte = Encoding.UTF8.GetBytes(config.SecretKey);
                    options.TokenValidationParameters = new TokenValidationParameters
                    {
                        ValidateIssuer = true,
                        ValidIssuer = config.ValidIssuer,
                        ValidateAudience = true,
                        ValidAudience = config.ValidAudience,
                        ValidateLifetime = true,
                        ClockSkew = TimeSpan.FromSeconds(300), // �����ݴ�ʱ��
                        ValidateIssuerSigningKey = true,
                        IssuerSigningKey = new SymmetricSecurityKey(secretByte),
                        RequireExpirationTime = true
                    };
                });
            services.AddSingleton<IAuthorizationHandler, PermissionAuthHandler>();
            return services;
        }
    }
}
